from twisted.internet.protocol import ServerFactory
from pymodbus.device import ModbusDeviceIdentification

from pymodbus.datastore import ModbusServerContext
from pymodbus.device import ModbusControlBlock
from pymodbus.device import ModbusAccessControl

from dcs_server_coder import DcsServerDecoder
from dcs_protocol import DcsProtocol
from dcs_framer import DcsModbusSocketFramer
from utils import *


class DcsFactory(ServerFactory):
    """
    Builder class for a modbus server

    This also holds the server datastore so that it is
    persisted between connections
    """

    protocol = DcsProtocol
    clients = []

    def __init__(self, store, framer=None, identity=None, **kwargs):

        self.decoder = DcsServerDecoder()
        self.framer = framer or DcsModbusSocketFramer
        self.store = store or ModbusServerContext()
        self.control = ModbusControlBlock()
        self.access = ModbusAccessControl()
        self.ignore_missing_slaves = True

        if isinstance(identity, ModbusDeviceIdentification):
            self.control.Identity.update(identity)

